package com.x.service.transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.x.dao.LocationDAO;
import com.x.model.Location;

@Component("locationService")
public class LocationService {
	@Autowired
	private LocationDAO locationDAO;

	public Map<String, Object> list(int pageIndex, int pageSize,
			List<String> wherePart, List<String[]> odrerPart) {
		Map<String, Object> list = locationDAO.list(pageIndex, pageSize,
				wherePart, odrerPart);
		return list;

	}

	public Boolean create(String province, String city, String district) {
		if (locationDAO.notExsit(province, city, district)) {
			locationDAO.create(province, city, district);
			return true;
		}
		return false;

	}

	public boolean notExsit(String province, String city, String district) {
		return locationDAO.notExsit(province, city, district);
	}

	public void delete(String id) {
		locationDAO.delete(id);
	}

	public void update(String province, String city, String district,
			String districtId) {
		locationDAO.update(province, city, district, districtId);

	}

	public List<String> getNodeByType(String type, int limit) {
		List<Location> locations = locationDAO.getLocationByType(type, limit);
		List<String> result = new ArrayList<>();
		for (Location location : locations) {
			String locationName = location.getName();
			result.add(locationName);
		}
		return result;
	}

	public List<String> getNodeSuggest(String name, String type) {
		List<Location> locations = locationDAO.getNodeSuggest(name, type);
		List<String> result = new ArrayList<>();
		for (Location location : locations) {
			String locationName = location.getName();
			result.add(locationName);
		}
		return result;
	}

	public List<Map<String, String>> getProvinceSelect() {
		List<Location> locations = locationDAO.getLocationByType("1", 0);
		List<Map<String,String>> result = new ArrayList<>();
		for (Location location : locations) {
			Map<String,String> data = new HashMap<>();
			String locationName = location.getName();
			String locationId = location.getId();
			data.put("name", locationName);
			data.put("id", locationId);
			result.add(data);
		}
		return result;
	}

	public List<Map<String, String>> getCitySelect(String provinceId) {
		Location province = locationDAO.getNodeById(provinceId);
		List<Location>cityList = province.getChildren();
		List<Map<String,String>> result = new ArrayList<>();
		for (Location city : cityList) {
			Map<String,String> data = new HashMap<>();
			String cityName = city.getName();
			String id = city.getId();
			data.put("name", cityName);
			data.put("id", id);
			result.add(data);
		}
		return result;
	}

}
